package com.sgzn.sgpay.aop;

import com.sgzn.sgpay.enums.AppName;
import com.sgzn.sgpay.util.SerialNoUtil;
import com.sgzn.sgpay.util.ValidateUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.MDC;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.net.Socket;

/**
 * 接口服务类AOP
 * @author zhongzhongyong
 * @version Id: ServiceAop.java, v 0.1 2018/4/3 15:21 zhongzhongyong Exp $$
 */
@Aspect
@Service
@Slf4j
public class TcpServiceAop {

    @Resource
    private ValidateUtil validateUtil;

    @Pointcut(value = "execution(public void com.sgzn.sgpay.service.tcp.impl.*.*(..)) && args(recvBuffer,socket,..)")
    private void tcpServicePointcut(String  recvBuffer, Socket socket) {
        //do nothing here
    }

    @Around("tcpServicePointcut(recvBuffer,socket)")
    public void aroundMethod(ProceedingJoinPoint jp, String  recvBuffer, Socket socket) throws Throwable {
        long startMillis = System.currentTimeMillis();


        String className = jp.getTarget().getClass().getSimpleName();
        String methodName = jp.getSignature().getName();
        Object[] args = jp.getArgs();

        //获取initiationID
        String initiationID = SerialNoUtil.generateSerialNo(AppName.SGW);

        try {
            MDC.put("initiationID", initiationID);
            // 1. 校验
            for(int i=0, length = args.length; i<length; i++){
                if (args[i] == null){
                    throw new IllegalArgumentException("Request must be not null");
                } else {
                    validateUtil.validate(args[i]);
                }
            }
            log.info("recvBuffer: {}", recvBuffer.toString());
            jp.proceed();
        } catch (Exception e) {
            log.error("Here throw an Exception:", e);
        }
        log.info("call[{}][{}][{}ms][{}][{}]RESPONSE:Result[{}]", className, methodName, System.currentTimeMillis() - startMillis);
    }

}
